package xjy.smartcommunity.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;

import xjy.smartcommunity.R;
import xjy.smartcommunity.util.HttpUtils;
import xjy.smartcommunity.util.SharedPrefUtils;

public class MainActivity extends AppCompatActivity {
    private NavigationView navigationView;
    private DrawerLayout mdrawerLayout;
    private TextView homeName;
    private TextView homeAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    //设置背景图片的透明度
        View v = findViewById(R.id.activity_main);
        v.getBackground().setAlpha(40);

        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            //修改图标
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu3);
        }
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("智慧社区");
        //主界面显示个人信息
        homeName = (TextView) findViewById(R.id.home_name);
        homeAddress = (TextView) findViewById(R.id.home_address);
        mdrawerLayout = (DrawerLayout) findViewById(R.id.activity_main);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        //侧导航栏的点击事件
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_person:
                        toPinfoShow();//跳转个人显示界面（只读）
                        break;
                    case R.id.nav_setting:
                        toSettingShow();//跳转设置修改列表界面
                        break;
                    case R.id.nav_back:
                        logoutBtnOnClick();//退出
                        break;
                    default:
                        break;
                }
                mdrawerLayout.closeDrawers();
                return true;
            }
        });
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                homePersonalInfo();
            }
        });
        thread.start();
    }
    //相数据库中调登录用户的姓名、住址用于主界面的显示
    private void homePersonalInfo() {
        String urlStr = getString(R.string.server_host) + "/getUserByUsername.do";
        String errMsg = "";
        Bundle bundle = new Bundle();
        try {
            HashMap<String, String> paras = new HashMap<>();
            String username = SharedPrefUtils.getValFromSP(this, SharedPrefUtils.username);
            paras.put("username", username);
            JSONObject json = HttpUtils.requestJson(this, urlStr, paras, false);
            if (json.getInt("status") != 0)
                throw new Exception(json.getString("message"));
            bundle.putString("username", username);
            JSONArray jsonArray = json.getJSONArray("data");
            if (jsonArray.length() == 0)
                throw new Exception("当前用户不存在");
            JSONObject user = jsonArray.getJSONObject(0);
            bundle.putString("name", user.getString("name"));
            bundle.putString("address", user.getString("address"));
        } catch (Exception ex) {
            errMsg = ex.getMessage();
            if (errMsg == null || errMsg.length() == 0)
                errMsg = "请求失败";
        }
        bundle.putString("errMsg", errMsg);
        Message msg = new Message();
        msg.setData(bundle);
        showHomeInfoHandler.sendMessage(msg);
    }
    private Handler showHomeInfoHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String errMsg = msg.getData().getString("errMsg");
            if (errMsg.length() > 0) {
                Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_SHORT).show();
                return;
            }
            Bundle bundle = msg.getData();
            homeName.setText(bundle.getString("name"));
            homeAddress.setText(bundle.getString("address"));
        }
    };

    /***
     * 主界面下部分导航栏的点击事件
     * 跳转到主界面
     * @param view
     */
    public void ImgHomeOnClick(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
    /***
     * 主界面下部分导航栏的点击事件
     * 跳转预留1
     * @param view
     */
    public void ImgYuliu1OnClick(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
    /***
     * 主界面下部分导航栏的点击事件
     * 跳转预留2
     * @param view
     */
    public void ImgYuliu2OnClick(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
    /***
     * 主界面下部分导航栏的点击事件
     * 跳转个人信息显示界面
     * @param view
     */
    public void ImgAboutOnClick(View view) {
        Intent intent = new Intent(this, PinfoShowActivity.class);
        startActivity(intent);
    }

    public void dangJianBtnOnClick(View view) {
        Intent intent = new Intent(this, DangJianActivity.class);
        startActivity(intent);
    }

    public void tiJianBtnOnClick(View view) {
        Intent intent = new Intent(this, TiJianActivity.class);
        startActivity(intent);
    }

    public void wuYeBtnOnClick(View view) {
        Intent intent = new Intent(this, WuYeActivity.class);
        startActivity(intent);
    }

    private void toPinfoShow() {
        Intent intent = new Intent(this, PinfoShowActivity.class);
        startActivity(intent);
    }
    private void toSettingShow() {
        Intent intent = new Intent(this, SettingActivity.class);
        startActivity(intent);
    }

    //个人信息展示，打算转移到侧边框中
    private void toPersonalInfo() {
        Intent intent = new Intent(this, PersonalInfoActivity.class);
        startActivity(intent);
    }

    public void logoutBtnOnClick() {
        SharedPrefUtils.putValToSP(this, SharedPrefUtils.sessionId, "");
        this.finish();
    }

    /**
     * 对侧边栏按钮进行处理，打开侧边栏
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //设置背景透明度
//        View v = findViewById(R.id.header);
//        v.getBackground().setAlpha(200);
        switch (item.getItemId()) {
            case android.R.id.home:
                mdrawerLayout.openDrawer(GravityCompat.START);//展开侧边菜单
                break;
            default:
        }
        return true;
    }

    /**
     * 对返回键进行处理，如果侧边栏打开则关闭侧边栏，否则关闭 activity
     */
    @Override
    public void onBackPressed() {
        if (mdrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mdrawerLayout.closeDrawers();
        } else {
            finish();
        }
    }
}
